import React from 'react';
import { StyleSheet, View, Text, Image, FlatList, Dimensions } from 'react-native';
import ActivityIndicatorTest from '../components/ActivityIndicatorTest'

const MOCKED_MOVIES_DATA = [
  {
    title: '标题',
    year: '2015',
    posters: {
      thumbnail:
        'https://res11.noxgroup.com/player/www/2019/6/18/cc00d6e120ade756a7e72493e03b191a.jpg'
    }
  }
]

// let REQUEST_URL =
//   'https://github.com/facebook/react-native/blob/0.5-stable/docs/MoviesExample.json'
let REQUEST_URL = 'http://192.168.43.17:3000/movies'

export default class Movie extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      data: [],
      loaded: false
    }

    this.fetchData = this.fetchData.bind(this)
  }

  componentDidMount() {
    this.fetchData()
  }

  fetchData() {
    fetch(REQUEST_URL)
      .then(response => {
        if (response.ok) {
          return response.clone().json()
        }
        throw new Error('Network response was not ok.')
      })
      .then(resp => {
        this.setState({
          data: this.state.data.concat(resp),
          loaded: true
        })
      })
      .catch(e => {
        console.error(e)
      })
  }

  render() {
    if (!this.state.data.length) {
      return this.renderLoadingView()
    } else {
      return (
        <View>
          <FlatList
            data={this.state.data}
            renderItem={this.renderMovie}
            keyExtractor={(item) => item.id}
            style={styles.list}
          />
        </View>
      )
    }
  }

  renderLoadingView() {
    return (
      <View style={styles.container}>
        <ActivityIndicatorTest></ActivityIndicatorTest>
        <Text style={{flex: 1}}>正在加载数据……</Text>
      </View>
    )
  }

  renderMovie = ({ item }) => {
    return (
      <View style={styles.container}>
        <Image
          source={{
            uri: item.posters.thumbnail
          }}
          style={styles.thumbnail}
        />
        <View style={styles.rightContainer}>
          <Text style={styles.title}>{item.title}</Text>
          <Text style={styles.year}>{item.year}</Text>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: Dimensions.get('window').width,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    marginBottom: 10,
    paddingLeft: 5,
    borderBottomWidth: 1,
    borderBottomColor: '#cccccc',
    backgroundColor: '#F5FCFF'
  },
  rightContainer: {
    flex: 1
  },
  list: {
    paddingTop: 20,
    backgroundColor: '#F5FCFF'
  },
  thumbnail: {
    width: 53,
    height: 81
  },
  title: {
    fontSize: 20,
    marginBottom: 8,
    textAlign: 'center'
  },
  year: {
    textAlign: 'center'
  }
})
